#!/usr/bin/env python3
import sys
import os
from scapy.all import sniff, get_if_list
from scapy.all import Packet
from scapy.all import IP, TCP, UDP
from scapy.layers.inet import _IPOption_HDR


class NetworkSniffer:
    """Network packet sniffer targeting specific destination ports"""
    
    def __init__(self):
        self.interface = self._find_interface()
    
    def _find_interface(self):
        """Discover first available Ethernet interface containing 'eth0'"""
        interfaces = [iface for iface in get_if_list() if "eth0" in iface]
        if not interfaces:
            print("eth0 interface not found")
            sys.exit(1)
        return interfaces[0]
    
    def process_packet(self, packet, target_port):
        """Handle packets matching the target destination port"""
        if (TCP in packet and packet[TCP].dport == target_port) or \
           (UDP in packet and packet[UDP].dport == target_port):
            print("Packet received:")
            packet.show2()
            if packet.load:
                print(packet.load)
            sys.stdout.flush()
    
    def launch(self, port):
        """Begin packet sniffing on the specified port"""
        print(f"Monitoring {self.interface} for port {port}")
        sniff(iface=self.interface, prn=lambda pkt: self.process_packet(pkt, port))


def main():
    if len(sys.argv) != 2:
        print("Usage: python3 sniffer.py <port>")
        sys.exit(1)
    
    try:
        target_port = int(sys.argv[1])
        sniffer = NetworkSniffer()
        sniffer.launch(target_port)
    except ValueError:
        print("Error: Port must be an integer")
        sys.exit(1)


if __name__ == '__main__':
    main()